using UnityEngine;
using UnityEngine.UI;
using System;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks; // 需要安装 UniTask 包

public class ResourceLoader2 : MonoBehaviour
{
    [Header("UI References")]
    [SerializeField] private Button loadButton;
    [SerializeField] private Button cancelButton;
    [SerializeField] private Slider progressSlider;
    [SerializeField] private Text statusText;
    public GameObject targetObject; // 目标游戏对象，即方形游戏物体
    private bool _isUserCancelled = false;
    private bool _isLoading = false;
    private CancellationTokenSource _cts;

    private void Start()
    {
        loadButton.onClick.AddListener(StartLoading);
        cancelButton.onClick.AddListener(CancelLoading);
        cancelButton.gameObject.SetActive(false);
    }

    private async void StartLoading()
    {
        if (_isLoading) return;
        _isLoading = true;
        // 初始化状态
        loadButton.interactable = false;
        cancelButton.gameObject.SetActive(true);
        progressSlider.value = 0;
        statusText.text = "准备加载...";
        
        // 创建新的 CancellationTokenSource
        _cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
        // _cts.RegisterTo(this.GetCancellationTokenOnDestroy()); // 绑定到组件生命周期

        try
        {
            await Task.Delay(500, _cts.Token);
            // 开始加载并等待结果
            var loadedAsset = await LoadAssetWithProgressAsync("Textures/MyTexture", _cts.Token);
            // 尝试将 loadedAsset 转换为 Texture2D 类型
            Texture2D texture = loadedAsset as Texture2D;
            SpriteRenderer spriteRenderer = targetObject.GetComponent<SpriteRenderer>();
            if (spriteRenderer != null)
            {
                Sprite sprite = Sprite.Create((Texture2D) texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                spriteRenderer.sprite = sprite;
            }
            Debug.Log(texture);
            // 加载成功后的处理（自动回到主线程）
            statusText.text = $"加载完成: {loadedAsset.name}";
        }
        catch (OperationCanceledException)
        {
            if (_isUserCancelled)
            {
                statusText.text = "加载已被用户主动取消";
                Debug.Log("用户主动取消了加载");
            }
            else
            {
                statusText.text = "加载因超时被取消";
                Debug.Log("加载因超时被取消");
            }
        }
        catch (System.Exception ex)
        {
            statusText.text = $"加载失败: {ex.Message}";
            Debug.LogError($"加载错误: {ex}");
        }
        finally
        {
            // 重置状态
            loadButton.interactable = true;
            cancelButton.gameObject.SetActive(false);
            _cts?.Dispose();
            _cts = null;
        }
    }

    private void CancelLoading()
    {
        _isUserCancelled = true;
        _cts?.Cancel();
    }

    private async UniTask<UnityEngine.Object> LoadAssetWithProgressAsync(string path, CancellationToken token)
    {
        // 第一阶段：准备加载（主线程）
        statusText.text = "正在初始化...";
        await UniTask.Yield(); // 确保回到主线程

        // 第二阶段：异步加载资源
        var loadOperation = Resources.LoadAsync<Texture2D>(path);

        // 创建进度报告器
        var progress = Progress.Create<float>(p =>
        {
            progressSlider.value = p;
            Debug.Log($"加载中... {p:P0}");
            statusText.text = $"加载中... {p:P0}";
        });

        // 等待加载完成（带取消和进度）
        await loadOperation.ToUniTask(progress, cancellationToken: token);

        // 第三阶段：验证结果
        if (loadOperation.asset == null)
        {
            throw new System.IO.FileNotFoundException($"资源未找到: {path}");
        }

        return loadOperation.asset;
    }

    private void OnDestroy()
    {
        _cts?.Cancel();
        _cts?.Dispose();
    }
    
}